/**
 * FormFieldEditor
 */
layui.define(['FormField', 'yunj'], function (exports) {

    let FormField = layui.FormField;

    class FormFieldEditor extends FormField {

        constructor(options = {}) {
            super(options);
            this.editorId = null;    // 富文本容器id
            this.editor = null;       // 富文本对象
        }

        defineExtraArgs() {
            let that = this;
            return {
                // 配置详见ckeditor
                toolbar: [
                    'Source', '-', 'Undo', 'Redo', '-', 'Preview', '-', 'SelectAll', '-', 'Bold', 'Italic', 'Underline', 'Strike', '-',
                    'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',
                    'BidiLtr', 'BidiRtl', '-', 'Link', 'Image', 'CodeSnippet', '-', 'Styles', 'Format', 'Font', 'FontSize', '-',
                    'TextColor', 'BGColor', '-', 'Maximize'
                ]
            };
        }

        handleArgs(args) {
            let that = this;
            let defaultConfig = that.defineExtraArgs();
            if (args.toolbar > 0) {
                args.toolbar = yunj.arrayIntersect(args.toolbar, defaultConfig.toolbar);
            } else {
                args.toolbar = defaultConfig.toolbar
            }
            return args;
        }

        defineBoxHtml() {
            let that = this;
            return `<div class="layui-form-item yunj-form-item yunj-form-item-label-width-fill" id="${that.id}">__layout__</div>`;
        }

        layoutControl() {
            let that = this;
            return `<div class="layui-input-inline yunj-form-item-control"><textarea id="${that.editorId}"></textarea></div>`;
        }

        async renderBefore() {
            let that = this;
            that.editorId = `${that.id}_editor`;
            await yunj.includeJs('/static/yunj/libs/ckeditor/ckeditor.js');
            return 'done';
        }

        renderDone() {
            let that = this;
            CKEDITOR.replace(that.editorId, {
                filebrowserUploadUrl: yunj.fileUploadUrl("ckeditor"),
                filebrowserImageUploadUrl: yunj.fileUploadUrl("ckeditor"),
                toolbar: [
                    {
                        name: 'init',
                        items: that.args.toolbar,
                    }
                ],
                readOnly: that.args.readonly
            });
            that.editor = CKEDITOR.instances[that.editorId];
        }

        async setValue(val = '') {
            let that = this;
            that.editor.setData(val);
        }

        getValue() {
            let that = this;
            return that.editor.getData();
        }

    }

    exports('FormFieldEditor', FormFieldEditor);
});